package com.zhugang.week01;

/**
 * @program algorithms
 * @description: IP地址无效化
 * @author: chanzhugang
 * @create: 2022/03/13 22:07
 */
public class IpAddress {

    public static void main(String[] args) {
        IpAddress ipAddress = new IpAddress();
        String address = "123.92.2.34";
        String str = ipAddress.defangIpAddr(address);

        String str2 = ipAddress.defangIpAddr2(address);
        System.out.println(str);
        System.out.println(str2);

    }

    /**
     * 给一个有效的ipv4地址address，返回这个ip地址的无效化版本（其实使用"[.]"替换每个"."）。
     */
    public String defangIpAddr(String address) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < address.length(); i++) {
            char c = address.charAt(i);
            if (c == '.') {
                builder.append("[.]");
            } else {
                builder.append(c);
            }
        }
        return builder.toString();
    }

    public String defangIpAddr2(String address) {
        // 申请一个新的数组,长度是愿数组 + 6
        char[] origin = address.toCharArray();
        char[] newStr = new char[origin.length + 6];
        int k = 0;
        for (int i = 0; i < origin.length; i++) {
            if (origin[i] != '.') {
                newStr[k] = origin[i];
                k++;
            } else {
                newStr[k++] = '[';
                newStr[k++] = '.';
                newStr[k++] = ']';
            }
        }
        return new String(newStr);
    }
}